// Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/new_tab_page/chrome_colors/chrome_colors_service.h"

#include "base/metrics/histogram_functions.h"
#include "base/metrics/histogram_macros.h"
#include "chrome/browser/new_tab_page/chrome_colors/generated_colors_info.h"
#include "chrome/browser/new_tab_page/chrome_colors/selected_colors_info.h"
#include "chrome/browser/themes/theme_service_factory.h"

namespace chrome_colors {

const int kDefaultColorId = -1;
const int kOtherColorId = 0;

ChromeColorsService::ChromeColorsService(Profile* profile)
    : theme_service_(ThemeServiceFactory::GetForProfile(profile)) {}

ChromeColorsService::~ChromeColorsService() = default;

// static
int ChromeColorsService::GetColorId(const SkColor color) {
  for (chrome_colors::ColorInfo color_info :
       chrome_colors::kGeneratedColorsInfo) {
    if (color == color_info.color)
      return color_info.id;
  }

  return kOtherColorId;
}

// static
void ChromeColorsService::RecordColorOnLoadHistogram(SkColor color) {
  UMA_HISTOGRAM_ENUMERATION("ChromeColors.ColorOnLoad", GetColorId(color),
                            kNumColorsInfo);
}

void ChromeColorsService::ApplyDefaultTheme(content::WebContents* tab) {
  SaveThemeRevertState(tab);
  theme_service_->UseDefaultTheme();
}

void ChromeColorsService::ApplyAutogeneratedTheme(SkColor color,
                                                  content::WebContents* tab) {
  SaveThemeRevertState(tab);
  theme_service_->BuildAutogeneratedThemeFromColor(color);
}

void ChromeColorsService::RevertThemeChangesForTab(content::WebContents* tab) {
  if (dialog_tab_ != tab)
    return;
  RevertThemeChangesInternal();
}

void ChromeColorsService::RevertThemeChanges() {
  RevertThemeChangesInternal();
}

void ChromeColorsService::ConfirmThemeChanges() {
  prev_theme_reinstaller_ = nullptr;
  dialog_tab_ = nullptr;
}

void ChromeColorsService::RevertThemeChangesInternal() {
  if (prev_theme_reinstaller_) {
    prev_theme_reinstaller_->Reinstall();
    prev_theme_reinstaller_ = nullptr;
    dialog_tab_ = nullptr;
  }
}

void ChromeColorsService::SaveThemeRevertState(content::WebContents* tab) {
  // TODO(crbug.com/980745): Support theme reverting for multiple tabs.
  if (!prev_theme_reinstaller_) {
    prev_theme_reinstaller_ = theme_service_->BuildReinstallerForCurrentTheme();
    dialog_tab_ = tab;
  }
}

void ChromeColorsService::Shutdown() {
  RevertThemeChangesInternal();
}

}  // namespace chrome_colors
